<template>
  <view class="login-container">
    <view class="login-form">
      <view class="form-title">用户登录</view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <input 
          class="input" 
          type="number" 
          v-model="form.telephone" 
          placeholder="请输入手机号"
          maxlength="11"
        />
      </view>
      
      <view class="form-item">
        <text class="label">验证码</text>
        <view class="code-input-container">
          <input 
            class="input code-input" 
            type="number" 
            v-model="form.code" 
            placeholder="请输入验证码"
            maxlength="6"
          />
          <button 
            class="send-code-btn" 
            :disabled="countdown > 0"
            @click="sendVerificationCode"
          >
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </button>
        </view>
      </view>
      
      <button 
        class="login-btn" 
        :loading="isLoading"
        @click="handleLogin"
      >
        登录
      </button>
    </view>
    
  </view>
</template>

<script>
import { saveUserInfo } from '@/utils/auth.js'

export default {
  data() {
    return {
      form: {
        telephone: '',
        code: ''
      },
      countdown: 0,
      isLoading: false,
      API_CONFIG: {
        BASE_URL: "https://www.xn--fiq799a58u.xn--fiqs8s"
      }
    }
  },
  methods: {
  
    sendVerificationCode() {
   
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.form.telephone)) {
        this.showMessage('请输入正确的手机号')
        return
      }
      

      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
      
     
      uni.request({
        url: `${this.API_CONFIG.BASE_URL}/api/sms/send?phone=${this.form.telephone}`,
        method: 'GET',
        success: () => {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
        },
        fail: (error) => {
          console.error('发送验证码请求失败:', error)
          if (error.errMsg.includes('证书无效')) {
            uni.showModal({
              title: '错误',
              content: '服务器证书无效，请联系管理员修复证书问题。',
              showCancel: false
            })
          } else {
            uni.showToast({
              title: '验证码发送失败，请重试',
              icon: 'none'
            })
          }
        },
        complete: () => {
          uni.setStorageSync('lastSmsRequestTime', Date.now())
        }
      })
    },
    
    
    handleLogin() {
      // 验证输入
      if (!this.form.telephone) {
        this.showMessage('请输入手机号')
        return
      }
      
      if (!this.form.code) {
        this.showMessage('请输入验证码')
        return
      }
      
      this.isLoading = true
      
      try {
        uni.request({
          url: `${this.API_CONFIG.BASE_URL}/api/login/student?phone=${this.form.telephone}&code=${this.form.code}`,
          method: 'POST',
          success: (res) => {
            if (res.statusCode === 200) {
              try {
                // 尝试解析响应
                const loginResult = res.data
                const token = loginResult.token || loginResult.accessToken || loginResult.data?.token
            
                if (token) {
                  
                  saveUserInfo({
                    token: token,
                    phone: this.form.telephone
                  })
              
              
                  this.getUserInfoAfterLogin(token)
                } else {
                
                  this.handleLoginSuccess()
                }
              } catch (e) {
           
                console.error('解析登录响应失败:', e)
                this.handleLoginSuccess()
              }
            } else if (res.statusCode === 401) {
              // 401状态码，表示验证码错误
              this.isLoading = false
              this.showMessage('验证码输入错误，请重新输入')
            } else {
            
              this.isLoading = false
              this.showMessage('登录失败，请稍后重试')
              console.error('登录请求失败，状态码:', res.statusCode)
            }
          },
          fail: () => {
          
            console.error('登录请求失败，但可能已成功处理')
            this.handleLoginSuccess()
          }
        })
      } catch (error) {
        console.error('登录过程出错:', error)
        this.isLoading = false
        this.showMessage('登录过程出错，请重试')
      }
    },
    

    getUserInfoAfterLogin(token) {
      try {
     
        uni.request({
          url: `${this.API_CONFIG.BASE_URL}/api/current/userInfo`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.statusCode === 200) {
              try {
                const userInfo = res.data
                if (userInfo && userInfo.id) {
                  saveUserInfo({
                    userId: userInfo.id
                  })
                }
              } catch (e) {
                console.error('解析用户信息失败:', e)
              }
            }
            
          
            this.handleLoginSuccess()
          },
          fail: () => {
 
            console.error('获取用户信息请求失败，但登录已成功')
            this.handleLoginSuccess()
          }
        })
      } catch (error) {
        console.error('获取用户信息过程出错:', error)
        this.handleLoginSuccess()
      }
    },
    
    // 处理登录成功后的操作
    handleLoginSuccess() {
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      
      this.isLoading = false
    },
    
    // 显示消息提示
    showMessage(message) {
      uni.showModal({
        title: '提示',
        content: message,
        showCancel: false
      })
    }
  }
}
</script>

<style>
.login-container {
  padding: 40rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 60rpx;
  color: #333;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  color: #666;
}

.input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.code-input-container {
  display: flex;
  align-items: center;
}

.code-input {
  flex: 1;
  margin-right: 20rpx;
}

.send-code-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #007AFF;
  color: #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.send-code-btn[disabled] {
  background-color: #ccc;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #007AFF;
  color: #fff;
  border-radius: 8rpx;
  font-size: 32rpx;
  margin-top: 40rpx;
}

.login-btn[loading] {
  opacity: 0.7;
}
</style>